package com.batchengine.startup;

import com.batchengine.BatchEngine;
import static com.batchengine.BatchEngine.setEngine;
import com.batchengine.Server;
import com.batchengine.service.Service;
import static com.batchengine.util.LoggingFactory.createLogger;
import com.batchengine.util.SocketListener;
import org.apache.log4j.Logger;

import java.io.IOException;
import static java.lang.Class.forName;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by sunil.incubator@yahoo.com.
 * User: sunil.kalva
 * Date: Jul 11, 2009
 */
public class BatchServer extends Server {

    private static final Logger logger = createLogger();

    /**
     * Maps port numbers to their listener threads.
     */
    protected Map<String, SocketListener> listeners;

    /**
     * Creates a <tt>Server</tt> object.
     */
    public BatchServer() {
        listeners = new ConcurrentHashMap<String, SocketListener>();
    }

    /**
     * Starts a service that does not require authentication.
     *
     * @param service the service to start
     * @param port    the port of the service
     */
    protected synchronized void startService(Service service, int port) throws IOException {
        startService(service, port, null);
    }

    /**
     * Starts a service that requires authentication.
     *
     * @param service  the service to start
     * @param port     the port of the service
     * @param password the password needed for authentication
     */
    protected synchronized void startService(Service service, int port, String password) throws IOException {
        startService(service, port, password, false);
    }

    /**
     * This method is used for to start the user defined modules
     */
    protected void startup() throws SQLException, UnknownHostException {

        logger.debug("@@@@@@@@@@@@@@ starting the server " + InetAddress.getLocalHost().getHostAddress() + " @@@@@@@@@@@@@@");
        BatchhEngineCache.loadCache();
    }

    public static void start(int port) {

        try {

            BatchServer server = new BatchServer();
            Service service = (Service) (forName(BatchEngine.class.getName()).newInstance());

            server.startup();
            server.startService(service, port);
            setEngine((BatchEngine) service);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

            // Sleep for 5 seconds before exiting. Gives the user some time to look at the error message.
//            try {
//                Thread.sleep(5000);
//            } catch (Exception ex) {
//                ex.printStackTrace();
//            }
        }
    }

}
